package com.thorqq.translation.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log
{
	private static final int LOG_LEVEL_DEBUG = 0;
	private static final int LOG_LEVEL_INFO = 1;
	private static final int LOG_LEVEL_WARN = 2;
	private static final int LOG_LEVEL_ERROR = 3;
	
	private static Logger mLogger = null;
	private static StringBuffer mBuf = new StringBuffer();
	
	public static void init()
	{
		PropertyConfigurator.configure("cfg/log4j.properties");
		mLogger = Logger.getLogger("Log");
	}
	
	public static boolean isDebugEnable()
	{
		return mLogger.isDebugEnabled();
	}
	
	public static void d(String... args)
	{
		if(mLogger.isDebugEnabled())
		{
			output(LOG_LEVEL_DEBUG, args);
		}
	}
	
	public static void i(String... args)
	{
		if(mLogger.isInfoEnabled())
		{
			output(LOG_LEVEL_INFO, args);
		}
	}

	public static void w(String... args)
	{
		output(LOG_LEVEL_WARN, args);
	}
	
	public static void e(String... args)
	{
		output(LOG_LEVEL_ERROR, args);
	}
	
	public static void ex(Exception ex)
	{
		StringWriter sw = null;
		PrintWriter pw = null;
		sw = new StringWriter();
		pw = new PrintWriter(sw);
		ex.printStackTrace(pw);
		pw.flush();
		sw.flush();
		
		output(LOG_LEVEL_ERROR, sw.toString());
	}
	
	public static void println(String... args)
	{
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		StringBuffer buf = new StringBuffer();
		buf.append("[").append(format.format(new Date())).append("]>>");
		for (String s : args)
		{
			buf.append(s);
		}
		System.out.println(buf.toString());
	}
	
	private static void output(int level, String... args)
	{
		//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
		//buf.append("[").append(format.format(new Date())).append("]>>");
		
//		if(mBuf.length() > 0)
//		{
//			mBuf.replace(0, mBuf.length(), "");
//		}
		mBuf.setLength(0);
		for (String s : args)
		{
			mBuf.append(s);
		}
		
		switch(level)
		{
		case LOG_LEVEL_DEBUG:
			mLogger.debug(mBuf.toString());
			break;
		case LOG_LEVEL_INFO:
			mLogger.info(mBuf.toString());
			break;
		case LOG_LEVEL_WARN:
			mLogger.warn(mBuf.toString());
		break;
		case LOG_LEVEL_ERROR:
			mLogger.error(mBuf.toString());
			break;
		default:
			mLogger.error(mBuf.toString());
			break;
		}
	}
}
